#!/usr/bin/python

#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.

from mojito_analysis import scan_parser

import event

import gzip
import random
import socket
import struct
import sys


def main(argv):
  do_all = False
  if len(argv) > 2:
    if 'all' in argv:
      do_all = True

  contacts_iter = scan_parser.slurp_responsive_nodes(argv[1])

#  ip = argv[2]
  outheader = open('bootstrap_nodes.h', 'w')
  outimpl = open('bootstrap_nodes.c', 'w')
  port = random.randint(1024, 65535)


  def do_send():
    for contact in contacts:
      client.send_ping_request(contact)
    print 'Pings away!'

  def print_responders():
    contacts = list(contacts_iter)
    random.shuffle(contacts)  # To make unresponsives clusters unlikely.
    nnodes = len(contacts)
    HDR_TEMPL = '''#ifndef BOOTSTRAP_NODES_H
#define BOOTSTRAP_NODES_H
#include "contact.h"
extern struct ContactAddress bootstrap_nodes[%d];
#endif /* BOOTSTRAP_NODES_H */
'''
    print >> outheader, HDR_TEMPL % nnodes
    IMPL_LEADIN = '''#include "bootstrap_nodes.h"
struct ContactAddress bootstrap_nodes[%d] = {
'''
    print >> outimpl, IMPL_LEADIN % nnodes

    def fixup_ip_addr(addr):
      return struct.unpack('<I', socket.inet_aton(addr))[0]

    for ip, port in contacts:
      print >> outimpl, '{NULL, {%dU}, %d},' % (fixup_ip_addr(ip), port)
    print >> outimpl, '};'

#  event.timeout(0.1, do_send)
#  event.timeout(30, print_responders)
#  event.dispatch()
  print_responders()


if __name__ == '__main__':
  main(sys.argv)
